﻿using DotNetty.Transport.Channels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DefaultDilimiterServer
{
    public class DelimiterServerHandler : SimpleChannelInboundHandler<string>
    {

        public override void ChannelActive(IChannelHandlerContext context)
        {
            // 这里用了\r\n做分隔符
            context.WriteAndFlushAsync(string.Format("welcome to {0} !\r\n", Dns.GetHostName()));
            context.WriteAndFlushAsync(string.Format("it is {0} now !\r\n", DateTime.Now));
        }

        public override void ChannelReadComplete(IChannelHandlerContext context)
        {
            // 接收完数据清空缓冲区
            context.Flush();
        }

        public override void ExceptionCaught(IChannelHandlerContext context, Exception exception)
        {
            // 发生异常,关闭通道
            context.DisconnectAsync();
            context.CloseAsync();
        }

        protected override void ChannelRead0(IChannelHandlerContext ctx, string msg)
        {
            string response;
            bool close = false;
            if (string.IsNullOrEmpty(msg))
            {
                response = "请输入一些内容!\r\n";
            }
            else if (string.Equals("bye", msg, StringComparison.OrdinalIgnoreCase))
            {
                response = "祝你今天过得愉快!\r\n";
                close = true;
            }
            else
            {
                response = "你是说:" + msg + "?\r\n";
            }

            // 将以上数据发送出去
            Task wait_task = ctx.WriteAndFlushAsync(response);
            if (close)
            {
                // 等待wait_task这个任务执行结束后关闭这个通道
                Task.WaitAll(wait_task);
                ctx.CloseAsync();
                Console.WriteLine("通道关闭");
            }
        }
    }
}
